﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TSV.Areas.Administration.Models;
using TSV.Library.Common;
using TSV.Models;
using System.IO;
using TSV.Library.Attributes;

namespace TSV.Areas.Administration.Controllers
{
    public class NewsController : BaseController
    {
        #region variable
        private NewsDao newsDao = new NewsDao();
        #endregion
        //
        // GET: /Administration/News/
        [CrmAuthorizeAttribute(Module = Modules.QL_Tin_Tuc, Rights = Permissions.Doc)]
        public ActionResult Index()
        {
            ViewData["ddlOrder"] = new SelectList(Constants.NEWS_ORDERS, "Value", "Text", string.Empty);
            return View();
        }

        public ActionResult GetListJQGrid(string p_text, string p_author, string p_fromdate, string p_todate)
        {

            #region JQGrid Params

            string sortColumn = (Request.Params[GridConstants.SORT_COLUMN]).ToString();
            string sortOrder = (Request.Params[GridConstants.SORT_ORDER]).ToString();
            int pageIndex = Convert.ToInt32(Request.Params[GridConstants.PAGE_INDEX]);
            int rowCount = Convert.ToInt32(Request.Params[GridConstants.ROW_COUNT]);
            #endregion
            #region search
            string key = null;
            string author = null;
            int newsOrder = 0;
            DateTime? fromDate = null;
            DateTime? toDate = null;
            if (!string.IsNullOrEmpty(p_text))
            {
                key = p_text;
            }
            if (!string.IsNullOrEmpty(p_author))
            {
                author = p_author;
            }
            if (!string.IsNullOrEmpty(p_fromdate))
            {
                fromDate = DateTime.Parse(p_fromdate);
            }
            if (!string.IsNullOrEmpty(p_todate))
            {
                toDate = DateTime.Parse(p_todate);
            }
            #endregion
            List<sp_GetNewsResult> list = newsDao.GetList(key, author, fromDate, toDate);

            int totalRecords = list.Count();
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)rowCount);

            var finalList = newsDao.Sort(list, sortColumn, sortOrder).Skip((pageIndex - 1) * rowCount).Take(rowCount);

            var jsonData = new
            {
                total = totalPages,
                page = pageIndex,
                records = totalRecords,
                rows = (
                    from m in finalList
                    select new
                    {

                        i = m.ID,
                        cell = new string[] {
                                m.ID.ToString(),
                                string.IsNullOrEmpty(m.Image) ? string.Empty: String.Format("<img src='{0}' width='100' height='100' />",Constants.UPLOAD_IMAGE_PATH + m.Image),
                                CommonFunc.SubStringRoundWord(m.Title,Constants.NEWS_ROUND_WORLD),
                                CommonFunc.SubStringRoundWord(m.Description,Constants.NEWS_ROUND_WORLD),
                                m.PostedDate.HasValue?m.PostedDate.Value.ToString(Constants.DATETIME_FORMAT):string.Empty,
                                m.Author,
                                CommonFunc.Button("edit","Chỉnh sửa","window.location='/Administration/News/Edit/"+m.ID+"';")
                            }
                    }
                ).ToArray()
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
        [CrmAuthorizeAttribute(Module = Modules.QL_Tin_Tuc, Rights = Permissions.Xoa)]
        public ActionResult DeleteList(string id)
        {
            Message msg = newsDao.DeleteList(id);
            ShowMessage(msg);
            return RedirectToAction("Index");
        }
        [CrmAuthorizeAttribute(Module = Modules.QL_Tin_Tuc, Rights = Permissions.Them)]
        public ActionResult Create()
        {
            //var principal = HttpContext.User as AuthenticationProjectPrincipal;
            ViewData["NewsOrder"] = new SelectList(Constants.NEWS_ORDERS, "Value", "Text", string.Empty);
            ViewData["Author"] = principal.UserData.UserName;
            return View();
        }

        private Message CheckUploadImage(HttpPostedFileBase file)
        {
            if (file == null)
                return null;
            Message msg = null;
            string ext = Path.GetExtension(file.FileName);
            if (file.ContentLength > Constants.UPLOAD_FILE_SIZE * 1024 * 1024)
            {
                msg = new Message(MessageConstants.E0012, MessageType.Error, Constants.UPLOAD_FILE_SIZE);
            }
            else if (!Constants.UPLOAD_ALLOW_IMG_EXT.Split(',').Contains(ext))
            {
                msg = new Message(MessageConstants.E0013, MessageType.Error, ext, Constants.UPLOAD_ALLOW_IMG_EXT, Constants.UPLOAD_FILE_SIZE);
            }
            return msg;

        }
        [CrmAuthorizeAttribute(Module = Modules.QL_Tin_Tuc, Rights = Permissions.Them)]
        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(New obj, HttpPostedFileBase file)
        {
            JsonResult result = new JsonResult();
            result.ContentType = "text/html";
            result.JsonRequestBehavior = JsonRequestBehavior.DenyGet;
            Message msg = CheckUploadImage(file);
            if (msg == null)
            {

                if (string.IsNullOrEmpty(obj.NewsContent))
                {
                    msg = new Message(MessageConstants.E0001, MessageType.Error, "Nội dung");
                }
                else
                {
                    string uniqueName = "";
                    if (file != null)
                    {
                        uniqueName = DateTime.Now.ToString(Constants.UNIQUE_TIME) + file.FileName;
                        string path = Server.MapPath(Constants.UPLOAD_IMAGE_PATH) + uniqueName;
                        file.SaveAs(path);
                    }
                    obj.Image = uniqueName;
                    msg = newsDao.Create(obj);
                    ShowMessage(msg);
                }
            }
            result.Data = msg;
            return result;
        }
        [CrmAuthorizeAttribute(Module = Modules.QL_Tin_Tuc, Rights = Permissions.Sua)]
        public ActionResult Edit(int id)
        {
            New obj = newsDao.GetByID(id);
            return View(obj);
        }
        [CrmAuthorizeAttribute(Module = Modules.QL_Tin_Tuc, Rights = Permissions.Sua)]
        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(New obj, HttpPostedFileBase file)
        {
            JsonResult result = new JsonResult();
            Message msg = null;
            result.ContentType = "text/html";
            result.JsonRequestBehavior = JsonRequestBehavior.DenyGet;
            New objDb = newsDao.GetByID(obj.ID);
            if (file != null)
            {
                msg = CheckUploadImage(file);
                if (msg == null)
                {
                    if (string.IsNullOrEmpty(obj.NewsContent))
                    {
                        msg = new Message(MessageConstants.E0001, MessageType.Error, "Nội dung");
                    }
                    else
                    {
                        if (objDb != null)
                        {
                            string uniqueName = DateTime.Now.ToString(Constants.UNIQUE_TIME) + file.FileName;
                            string path = Server.MapPath(Constants.UPLOAD_IMAGE_PATH) + uniqueName;
                            file.SaveAs(path);
                            string oldPath = Server.MapPath(Constants.UPLOAD_IMAGE_PATH) + objDb.Image;
                            System.IO.File.Delete(oldPath);
                            obj.Image = uniqueName;
                            msg = newsDao.Update(obj);
                            ShowMessage(msg);
                        }
                    }
                }
            }
            else
            {
                obj.Image = objDb.Image;
                msg = newsDao.Update(obj);
                ShowMessage(msg);
            }
            result.Data = msg;
            return result;
        }

    }
}
